package com.hjm.project.channel.invoice.service.impl;

import cn.hutool.http.HttpUtil;
import com.hjm.common.api.ls.leshua.LeShuaUtil;
import com.hjm.common.api.ls.leshua.entity.AddInvoice;
import com.hjm.common.api.ls.leshua.ls.ImageUtil;
import com.hjm.common.exception.BusinessException;
import com.hjm.common.utils.StringUtils;
import com.hjm.common.utils.fastdfs.FastDFSClient;
import com.hjm.common.utils.file.FileUploadUtils;
import com.hjm.common.utils.security.ShiroUtils;
import com.hjm.common.utils.text.Convert;
import com.hjm.framework.config.BlueConfig;
import com.hjm.framework.config.CustomConfig;
import com.hjm.project.agentInfo.agentInfo.utils.Utils;
import com.hjm.project.channel.invoice.domain.ChannelInvoice;
import com.hjm.project.channel.invoice.mapper.ChannelInvoiceMapper;
import com.hjm.project.channel.invoice.service.IChannelInvoiceService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电子发票信息Service业务层处理
 * 
 * @author maker-platform
 * @date 2025-03-19
 */
@Service
public class ChannelInvoiceServiceImpl implements IChannelInvoiceService {
    @Resource
    private ChannelInvoiceMapper channelInvoiceMapper;

    /**
     * 查询电子发票信息
     * 
     * @param id 电子发票信息ID
     * @return 电子发票信息
     */
    @Override
    public ChannelInvoice selectChannelInvoiceById(Integer id) {
        return channelInvoiceMapper.selectChannelInvoiceById(id);
    }

    /**
     * 查询电子发票信息列表
     * 
     * @param channelInvoice 电子发票信息
     * @return 电子发票信息
     */
    @Override
    public List<ChannelInvoice> selectChannelInvoiceList(ChannelInvoice channelInvoice) {
        List<ChannelInvoice> channelInvoices = channelInvoiceMapper.selectChannelInvoiceList(channelInvoice);
        for (ChannelInvoice invoice : channelInvoices) {
            invoice.setImagePath(CustomConfig.getImgUrl() + invoice.getImagePath());
        }
        //return channelInvoiceMapper.selectChannelInvoiceList(channelInvoice);
        return channelInvoices;
    }

    /**
     * 查询电子发票信息列表
     *
     * @param channelInvoice 电子发票信息
     * @return 电子发票信息 一个结果
     */
    @Override
    public ChannelInvoice selectChannelInvoiceOne(ChannelInvoice channelInvoice) {
        return channelInvoiceMapper.selectChannelInvoiceOne(channelInvoice);
    }

    /**
     * 新增电子发票信息
     * 
     * @param channelInvoice 电子发票信息
     * @return 结果
     */
    @Override
    public int insertChannelInvoice(MultipartFile file, ChannelInvoice channelInvoice)throws Exception  {
        if (file != null) {
            String fileName =  file.getOriginalFilename();
            if (fileName.endsWith(".jpg")||fileName.endsWith(".png")||fileName.endsWith(".gif")||fileName.endsWith(".GIF")||fileName.endsWith(".JPG")||fileName.endsWith(".PNG")) {
//                String urlName = FileUploadUtils.upload(BlueConfig.getInvoicePath(), file);
                //上传文件
                String urlName = uploadImg(file);
                channelInvoice.setImagePath(urlName);
            }else{
                throw  new BusinessException("图片上传失败,请重新上传");
            }
        }else{
            throw  new BusinessException("图片上传失败,未选择图片");
        }
        channelInvoice.setAgentId(CustomConfig.getSubAgentId());
        channelInvoice.setSubAgentId(channelInvoice.getApplyAgentId());
        return channelInvoiceMapper.insertChannelInvoice(channelInvoice);
    }
    public String uploadImg(MultipartFile imgFile) throws IOException {
        String clientName = imgFile.getOriginalFilename();
        if (StringUtils.isEmpty(clientName)) {
            return null;
        }
        String fileName = null;
        fileName = clientName.substring(clientName.indexOf("."), clientName.length());
        //临时文件
        File dfile = File.createTempFile("prefix", "_" + clientName);
        imgFile.transferTo(dfile);
        //上传至Fast的图片数据
        Map<String, String> metaList = new HashMap<String, String>();
        metaList.put("fileName", fileName);
        metaList.put("fileType", imgFile.getName());
        metaList.put("author", ShiroUtils.getSysUser().getLoginName());
        metaList.put("date", Utils.formateDate(2));//年月日 时分秒
        String fid = FastDFSClient.uploadFile(dfile, dfile.getName(), metaList);
        if (StringUtils.isEmpty(fid)) {
            throw  new BusinessException("图片上传失败,请重新上传");
        }
        return fid;
    }

    /**
     * 修改电子发票信息
     *
     * @param channelInvoice 电子发票信息
     * @return 结果
     */
    @Override
    public int updateChannelInvoice(MultipartFile file, ChannelInvoice channelInvoice) throws Exception {
        //判断格式是不是图片格式jpg png gif
        String fileName =  file.getOriginalFilename();
        if (file != null && StringUtils.isNotBlank(fileName)){
            if (fileName.endsWith(".jpg")||fileName.endsWith(".png")||fileName.endsWith(".gif")||fileName.endsWith(".GIF")||fileName.endsWith(".JPG")||fileName.endsWith(".PNG")) {
//                String urlName = FileUploadUtils.upload(BlueConfig.getInvoicePath(), file);
                //上传文件
                String urlName = uploadImg(file);
                channelInvoice.setImagePath(urlName);
            }else{
                throw  new BusinessException("图片上传失败,请重新上传");
            }
        }
        return channelInvoiceMapper.updateChannelInvoice(channelInvoice);
    }

    /**
     * 删除电子发票信息对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteChannelInvoiceByIds(String ids) {
        return channelInvoiceMapper.deleteChannelInvoiceByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除电子发票信息信息
     * 
     * @param id 电子发票信息ID
     * @return 结果
     */
    @Override
    public int deleteChannelInvoiceById(Integer id) {
        return channelInvoiceMapper.deleteChannelInvoiceById(id);
    }

    @Override
    public void sendChannel(ChannelInvoice channelInvoice) throws IOException {
        AddInvoice addInvoice = new AddInvoice();
        addInvoice.setAgentId(channelInvoice.getAgentId());
        addInvoice.setSubAgentId(channelInvoice.getSubAgentId());
        addInvoice.setSource(CustomConfig.getSource());
        addInvoice.setOperatorName("ls");
        addInvoice.setAmount(channelInvoice.getAmount());
//        addInvoice.setImageBase64Str(ImageUtil.encodeImageToBase64(BlueConfig.getInvoicePath() + channelInvoice.getImagePath().substring(channelInvoice.getImagePath().indexOf("invoice") + "invoice".length())));
        addInvoice.setImageBase64Str(convertImageToBase64(CustomConfig.getImgUrl() + channelInvoice.getImagePath()));
        int dotIndex = channelInvoice.getImagePath().lastIndexOf(".");
        String extension = (dotIndex == -1) ? "" : channelInvoice.getImagePath().substring(dotIndex + 1);
        addInvoice.setFileExt(extension);
        addInvoice.setInvoiceCode(channelInvoice.getInvoiceCode());
        addInvoice.setTaxpayerNo(channelInvoice.getTaxpayerNo());
        addInvoice.setInvoiceNo(channelInvoice.getInvoiceNo());
        addInvoice.setTaxRatio(channelInvoice.getTaxRatio());
        addInvoice.setTax(channelInvoice.getTax());
        addInvoice.setInvoiceTime(channelInvoice.getInvoiceTime());
        addInvoice.setInvoiceContent(channelInvoice.getInvoiceContent());
        addInvoice.setTrackingNo(channelInvoice.getTrackingNo());
        Map<String, Object> baseResult = LeShuaUtil.commonRemote(addInvoice, CustomConfig.getBaseUrl() + "/merchantinfo/v3/addInvoice", CustomConfig.getSignKey());
        if (StringUtils.equals(baseResult.get("resultCode").toString(), "0000")) {
            channelInvoice.setStatus(1);
        }else{
            channelInvoice.setStatus(2);
        }
        channelInvoiceMapper.updateChannelInvoice(channelInvoice);
    }
    public static String convertImageToBase64(String imagePath) throws IOException {
        // 通过 Hutool 下载图片字节流
        byte[] imageBytes = HttpUtil.downloadBytes(imagePath);
        // Base64 编码
        return Base64.getEncoder().encodeToString(imageBytes);
    }

}
